// miniprogram/pages/mine/payOrder/payOrder.js
const app = getApp()
const utils = require('../../../utils/util')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    meritsVirtues: '',
    fullName: '',
    mobile: '',
    chargeAmount: 0,
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.info('页面初始化时的全局参数为：',app.globalData)
    const moblie = app.globalData.phoneNumber
    const meritsVirtues = app.globalData.meritsVirtues
    const fullName = app.globalData.fullName
    if(moblie == '' || moblie == undefined){
      console.error('手机号有误.')
      wx.showToast({title:"页面初始化失败",icon: "error",duration: 2000})
      return;
    }
    if(meritsVirtues == '' || meritsVirtues ==undefined || meritsVirtues == null){
      console.error('请先绑定功德主名称.')
      wx.showToast({title:"请先绑定功德主名称",icon: "error",duration: 2000})
      return;
    }
    this.setData({meritsVirtues: meritsVirtues, fullName: fullName, moblie: moblie})
  },
  //确定支付按钮
  confirmChargeClickBtn: async function(e) {
    this.setData({loading: true})
    const payAmount = Number(this.data.chargeAmount) * 100
    if(payAmount <= 0){
      wx.showToast({title:"金额太小",icon: "error",duration: 1000})
      this.setData({loading: false})
      return;
    }
    const payment = await this.getPaymentCallCloud(payAmount)
    const reqPaymentResult = await this.requestPayment(payment)
    this.setData({loading: false})
    if(reqPaymentResult.errMsg == 'requestPayment:ok'){//如果支付成功,调用云函数更新支付状态
      console.info('支付成功.')
      return;
    }
    console.error('支付失败，返回的值为：',reqPaymentResult)
  },
  //获取payment
  getPaymentCallCloud: async function(totalFree){
    const curDateTime = await utils.formatDateOrTime(new Date(), "yyyyMMddHHmmss")
    const data = await this.getOrderNo()
    let newOrderNo = ''
    if(data){
      const orderNo = data.orderNo
      const order = orderNo.substring(orderNo.length - 5)
      const newOrder = (new Number(order)) + 1
      newOrderNo = await utils.formatterOrder(newOrder)
    }
    if(!data){
      newOrderNo = '00001'
    }
    return await new Promise(resolve => {
      const mobile = app.globalData.phoneNumber
      const kindPeopId = app.globalData.kindPeopleId
      const meritsVirtues = app.globalData.meritsVirtues
      wx.cloud.callFunction({
        name: 'pay',
        data: {
          reqType: 'getPayment',
          mobile: mobile,
          kindPeopId: kindPeopId,
          meritsVirtues: meritsVirtues,
          totalFee: totalFree,
          outTradeNo: 'MNO' + curDateTime + newOrderNo,//商户订单号32位
        },
        success: res => {
          console.log('获取payment的结果为：',res)
          if(res.result.payment){
            const payment = res.result.payment
            resolve(payment)
            return ;
          }
          wx.showToast({title:"操作失败",icon: "error",duration: 2000})
        },
        fail: () => {resolve(undefined)},
      })
    })
  },
  //获取当日最新订单号
  getOrderNo: async function(){
    return await new Promise(resolve=>{
      wx.cloud.callFunction({
        name: 'findCollectionById',
        data: { collectionName: 'paymentDetails', reqType: 'getDayOrderNo'},
        success: res => {
          const data = res.result.data
          console.log('返回的值为：',res)
          resolve(data)
        },
        fail: () => {resolve(undefined)},
      })
    })
  },
  //请求支付接口
  requestPayment: async function(payment) {
    return await new Promise(resolve=>{
      wx.requestPayment({
        ...payment,
        success (res) {
          console.log('支付成功.', res)
          resolve(res)
        },
        fail (err) {
          console.error('支付失败.', err)
          resolve(undefined)
        }
      })
    })
  },
   //输入框金额改变时触发
   chargeAmountChange: function(e) {
    console.log('e: ',e)
    let value = e.detail.value
    const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9][0-9]$)/;
    if(!reg.test(value)){
      value = value.replace(/[^\d\.]/g, ""); //清除"数字"和"."以外的字符
      value = value.replace(/^\./g, ""); //验证第一个字符是数字
      value = value.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
      value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
      value = value.replace(/(?!^[0]\.)^[0]/,"") //开头不等于“0.”且首位为0则替换，表达式且：(?=表达式A)表达式B，同时满足A和B
    }
    this.setData({chargeAmount: value})
  },
})